package com.longrise.android.upload_offline;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.common.DownloadConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.utils.AppUtil;


/**
 * Created by sujizhong on 16/3/2.
 */
public class DBDAO {

//    private static final String TAG = DBDAO.class.getSimpleName();

    private static DBDAO mDAO;

    private SQLiteDatabase mDataBase;
    private DBHelper mDBHelper;

    private static final String READ = "READ";
    private static final String WRITE = "WRITE";

    public static String DATABASE_STATUS = WRITE;

    private DBDAO() {
        mDBHelper = new DBHelper(AppUtil.getContext());
//        if (DATABASE_STATUS.equals(WRITE)) {
        openWrite();  //获取一个可以读写的数据库
//        } else {
//            openRead();
//        }
    }

    private void openRead() {
        try {
            mDataBase = mDBHelper.getReadableDatabase();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void openWrite() {
        try {
            mDataBase = mDBHelper.getWritableDatabase();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static DBDAO getInstance() {
        if (mDAO == null) {
            synchronized (DBDAO.class) {
                if (mDAO == null) {
                    mDAO = new DBDAO();
                }
            }
        }
        return mDAO;
    }

    public void close() {
        try {
            if (mDataBase != null && mDataBase.isOpen()) {
                mDataBase.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void isOpen() {
        try {
            if (mDataBase == null || !mDataBase.isOpen()) {
                openWrite();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void insert(String expiretime, String id, String studentno, String effecttime) {
        try {
            isOpen();
            if (mDataBase != null) {
                mDataBase.execSQL(DBSQL.INSERT, new Object[]{expiretime, id, studentno, effecttime});
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close();
        }
    }

    public void delete_All() throws Exception {
        try {
            isOpen();
            if (mDataBase != null) {
                mDataBase.execSQL(DBSQL.DELETE_ALL);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close();
        }
    }

    /**
     * @param studentno 学号
     * */
    public void deleteWhere_StudyrecordId(String studentno){
        try{
            isOpen();
            if(mDataBase != null){
                mDataBase.execSQL(DBSQL.DELETE, new String[]{studentno});
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            close();
        }
    }

    public Cursor query() {
        Cursor cursor = null;
        try {
            isOpen();
            if (mDataBase != null) {
                cursor = mDataBase.rawQuery(DBSQL.QUERY, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cursor;
    }

    public Cursor ID_Query(String id) throws Exception {
        isOpen();
        Cursor idc = null;
        if (mDataBase != null) {
            idc = mDataBase.rawQuery(DBSQL.ID_QUERY, new String[]{id});
        }
        return idc;
    }

    /**
     * video local player query study information
     */
    public EntityBean query_study(String... string) {
        if (TextUtils.isEmpty(string[0]) || TextUtils.isEmpty(string[1])) {
            return null;
        }
        isOpen();
        Cursor cursor = null;
        EntityBean bean = null;
        try {
            if (mDataBase != null) {
                cursor = mDataBase.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL + " where " + DownloadConstants.USERID + " = " + "'" + UserInfor.getInstance().getUserid() + "' and " + DownloadConstants.COURSEID + " = " + "'" + string[0] + "' and " + DownloadConstants.CWID + " = " + "'" + string[1] + "'", null);
                if (cursor != null && cursor.getCount() != 0) {
                    bean = new EntityBean();
                    cursor.moveToFirst();
                    cursor.moveToPrevious();
                    cursor.moveToNext();
                    String expiretiem = cursor.getString(cursor.getColumnIndex(DownloadConstants.EXPIRETIME));
                    String student = cursor.getString(cursor.getColumnIndex(DownloadConstants.STUDENTNO));
                    double effecttime = cursor.getDouble(cursor.getColumnIndex(DownloadConstants.TOTALTRAINTIME));
                    String id = cursor.getString(cursor.getColumnIndex(DownloadConstants.ID));
                    int isfinish = cursor.getInt(cursor.getColumnIndex(DownloadConstants.ISFINISHED));
                    bean.set("expiretime", expiretiem);
                    bean.set("studentno", student);
                    bean.set("effecttime", effecttime);
                    bean.set("id", id);
                    bean.set("isfinish", isfinish);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            close();
        }
        return bean;
    }

    /**
     * 根据userid 与 courseid查询出 cachepath
     */
    public EntityBean getLocalVideoCachePath(String courseid, String cwid) {
        EntityBean cacheBean = null;
        isOpen();
        Cursor cursor = null;
        try {
            if (mDataBase != null) {
                cursor = mDataBase.rawQuery(DBSQL.QUERY_QUERY_CACHEPATH, new String[]{UserInfor.getInstance().getUserid(), courseid, cwid});
                if (cursor != null && cursor.getCount() > 0) {
                    cursor.moveToFirst();
                    cursor.moveToPrevious();
                    cacheBean = new EntityBean();
                    while (cursor.moveToNext()) {
                        String cachepath = cursor.getString(cursor.getColumnIndex("cachepath"));
                        String cwName = cursor.getString(cursor.getColumnIndex("cwName"));
                        cacheBean.set("cachepath", cachepath);
                        cacheBean.set("cwName", cwName);

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            close();
        }
        return cacheBean;
    }

    /**
     * 课后练习提通过了的修改本地数据库状态
     */
    public void insertVideopass(String courseID, String cwID) {
        isOpen();
        ContentValues cv = new ContentValues();
        cv.put(DownloadConstants.VIDEOPASS, 1);
        Cursor cursor = null;
        try {
            if (mDataBase != null) {
                cursor = mDataBase.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL + " where courseID = ? and cwID = ? ", new String[]{courseID, cwID});
                while (cursor.moveToNext()) {
                    mDataBase.update(DownloadConstants.TBNAME_DOWNLOAD_DETAIL, cv, " courseID = ? and cwID = ? ", new String[]{courseID, cwID});
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            close();
        }
    }
}
